package ru.reaperoq.taskmanager.services

import org.springframework.security.crypto.password.PasswordEncoder
import org.springframework.stereotype.Service
import ru.reaperoq.taskmanager.models.User
import ru.reaperoq.taskmanager.repositories.UserRepository

@Service
class UserService(
    private val userRepository: UserRepository,
    private val passwordEncoder: PasswordEncoder
) {
    fun createUser(user: User): User? {
        val found = userRepository.existsByUsername(user.username)
        return if (found) {
            null
        } else {
            userRepository.save(user)
        }
    }

    fun loginUser(user: User): User? {
        val found = userRepository.findUserByUsername(user.username)
        return if (passwordEncoder.matches(user.password, found?.password)) {
            user
        } else {
            null
        }
    }

    fun findUserById(id: Long): User? =
        userRepository.findUserById(id)

    fun findAllUsers(): List<User> =
        userRepository.findAll().toList()
}